package com.fanfan.SmartPensionSystembackend.controller;

import com.fanfan.SmartPensionSystembackend.entity.User;
import com.fanfan.SmartPensionSystembackend.service.UserService;
import com.fanfan.SmartPensionSystembackend.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {

    @Autowired
    private UserService userService; // 调用 Service 层

    // 用于存储验证码的内存存储
    private ConcurrentHashMap<String, String> verificationCodes = new ConcurrentHashMap<>();

    // 注册功能
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        try {
            // 获取传入的验证码
            String providedCode = user.getCode();

            // 获取存储的验证码
            String storedCode = verificationCodes.get(user.getPhone());

            // 验证码校验
            if (providedCode == null || !providedCode.equals(storedCode)) {
                return ResponseUtil.error("验证码错误，请重新输入");
            }

            // 调用 Service 层完成注册逻辑
            boolean isSuccess = userService.registerUser(user);
            if (isSuccess) {
                return ResponseUtil.success("注册成功",null);
            } else {
                return ResponseUtil.error("注册失败，请稍后重试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.error("系统异常：" + e.getMessage());
        }
    }

    // 发送验证码功能
    @GetMapping("/sendCode/{phone}")
    public Map<String, Object> sendCode(@PathVariable String phone) {
        try {
            // 生成随机四位验证码
            Random random = new Random();
            int code = 1000 + random.nextInt(9000); // 生成1000到9999之间的随机数

            // 将验证码转换为字符串
            String codeStr = String.valueOf(code);

            // 存储验证码
            verificationCodes.put(phone, codeStr);

            // 这里可以添加发送验证码的逻辑，例如通过短信服务发送验证码到指定手机号码

            // 返回验证码
            Map<String, Object> response = new HashMap<>();
            response.put("phone", phone);
            response.put("code", codeStr);
            return ResponseUtil.success("验证码",response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.error("系统异常：" + e.getMessage());
        }
    }

    // 登录功能
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user) {
        try {
            // 调用 Service 层完成登录逻辑
            User loggedInUser = userService.loginUser(user.getUsername(), user.getPassword());
            if (loggedInUser != null) {
                return ResponseUtil.success("登录成功", loggedInUser);
            } else {
                return ResponseUtil.error("登录失败，用户名或密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.error("系统异常：" + e.getMessage());
        }
    }

    // 修改密码功能
    @PostMapping("/changePassword")
    public Map<String, Object> changePassword(@RequestBody Map<String, String> password) {
        try {
            String username = password.get("username");
            String oldPassword = password.get("oldPassword");
            String newPassword = password.get("newPassword");

            // 调用 Service 层完成密码修改逻辑
            boolean isSuccess = userService.updatePassword(username, oldPassword, newPassword);
            if (isSuccess) {
                return ResponseUtil.success("密码修改成功", null);
            } else {
                return ResponseUtil.error("旧密码不正确，请重新输入");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.error("系统异常：" + e.getMessage());
        }
    }

    // 获取所有员工信息
    @GetMapping("/getAllUsers")
    public Map<String, Object> getAllUsers() {
        try {
            List<User> userList = userService.getAllUsers();
            // 调用 Service 层获取所有员工信息
            return ResponseUtil.success("获取员工信息成功", userList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.error("系统异常：" + e.getMessage());
        }
    }

    // 更新员工信息
    @PostMapping("/updateUser")
    public Map<String, Object> updateUser(@RequestBody User user) {
        try {
            // 调用 Service 层更新员工信息
            boolean isSuccess = userService.updateUser(user);
            if (isSuccess) {
                return ResponseUtil.success("更新员工信息成功", null);
            } else {
                return ResponseUtil.error("更新员工信息失败，请稍后重试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.error("系统异常：" + e.getMessage());
        }
    }

    // 删除员工信息
    @DeleteMapping("/deleteUser")
    public Map<String, Object> deleteUser(@RequestParam String userId) {
        try {
            // 调用 Service 层删除员工信息
            boolean isSuccess = userService.deleteUser(userId);
            if (isSuccess) {
                return ResponseUtil.success("删除员工信息成功", null);
            } else {
                return ResponseUtil.error("删除员工信息失败，请稍后重试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.error("系统异常：" + e.getMessage());
        }
    }
}